package ml.coursedesign.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ml.coursedesign.common.lang.Result;
import ml.coursedesign.common.util.SubjectExcelListener;
import ml.coursedesign.entity.*;
import ml.coursedesign.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    SubjectService subjectService;
    @Autowired
    StudentService studentService;
    @Autowired
    SubjectGroupService subjectGroupService;
    @Autowired
    SelectSubjectService selectSubjectService ;
    @Autowired
    TeacherService teacherService;
    
    /**
     * 获得教师名单（仅仅是名单，不含敏感信息）
     * @return
     */
    @GetMapping("/list")
    public Result getAllTeachers() {
        List<Teacher> list = teacherService.list(null);
        list.forEach(teacher -> {
            teacher.setPassword("");
        });

        return Result.succ(list);
    }


    /**
     * 文件导入课题
     * @param file
     * @return
     */
    @PostMapping("add/by/file")
    public Result addSubjectByFile(@RequestParam("filename") MultipartFile file){
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        EasyExcel.read(fileName, SubjectImportData.class,new SubjectExcelListener()).sheet().doRead();
        return Result.succ();

    }

    /***
     * 手动添加课题操作
     * @param subject
     * @return
     */
    @PostMapping(value = "/insertSubject",produces = "application/json")
    public Result insertSubject(@RequestBody Subject subject){
        subject.setDeleted(0);
        boolean save = subjectService.save(subject);
        if(save){
            return Result.succ();
        }else {
            return Result.fail();
        }

    }
    /**
     * 修改课题
     * @param subject
     * @return
     */
    @PostMapping(value = "/updataSubject",produces = "application/json")
    public Result updataSubject(@RequestBody Subject subject){
        System.err.println(subject);
        String subjectId = subject.getSubjectName();
        System.err.println(subjectId);

        boolean update = subjectService.updateById(subject);
        if(update){
            return Result.succ();
        }else {
            return Result.fail();
        }
    }

    @DeleteMapping("/deleteSubject/{subjectId}")
    public Result deleteSubject(@PathVariable String subjectId){
        boolean delete = subjectService.removeById(subjectId);
        if(delete){
            return Result.succ();
        }else {
            return Result.fail();
        }

    }


    @GetMapping("get/group/members/info/{subjectid}/{classId}")
    public Result getGroupMembersInfoList(@PathVariable String subjectid,
                                          @PathVariable String classId){

        List<SelectSubject> groupList = selectSubjectService.getGroupfoList(subjectid,classId);
        List<Student> studnets = new ArrayList<>();
        for ( SelectSubject element: groupList) {
            String username = element.getStuId();
            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",username);
            Student student = studentService.getOne(queryWrapper);
            studnets.add(student);


        }
        return Result.succ(studnets);

    }
    @GetMapping("set/student/identity/{id}/{i}")
    public Result setStudentIdentity(@PathVariable String id,
                                     @PathVariable Integer i){

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",id);
        Student student = studentService.getOne(queryWrapper);
        student.setIdentity(i);
        boolean update = studentService.saveOrUpdate(student);
        boolean isSave = insertLeaderInfoToGroup(id,i);



        if(update && isSave){
            return Result.succ();
        }else {
            return Result.fail();
        }


    }
    @DeleteMapping("remove/member/{stuId}")
    public Result removeMemberFormGroup(@PathVariable String stuId){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",stuId);
        Student student = studentService.getOne(queryWrapper);
        student.setIdentity(0);

        QueryWrapper<SelectSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",stuId);
        boolean remove = selectSubjectService.remove(wrapper);
        if (remove){
           return Result.succ();
        }
        return Result.fail();


    }
    @GetMapping("select/student/by/like/{stuName}")
    public Result selectStudentInfoByLike(@PathVariable String stuName){
        List<Student> students = studentService.selectStudnetByLike(stuName);
        return Result.succ(students);

    }
    @PostMapping("add/group/member/{subjectId}")
    public Result  addGroupMember( @PathVariable String subjectId,@RequestBody Student student){
        String className = student.getClassName();
        String stuId = student.getUsername();
        String classid = String.valueOf(className.charAt(className.length()-2)) ;
        SelectSubject selectSubject = new SelectSubject();
        selectSubject.setSubjectId(subjectId);
        selectSubject.setStuId(stuId);
        selectSubject.setCourseClassId(classid);
        boolean save = selectSubjectService.save(selectSubject);
        if (save){
            return Result.succ();
        }
        return Result.fail();

    }
    @PostMapping("/get/subject/info/list")
    public Result getSubjectInfoVOList(@RequestBody SubjectInfoVO subjectInfoVO){

       List<SubjectInfoVO> subjectInfoVOList= selectSubjectService.getSubjectInfoVOList(subjectInfoVO);
        return Result.succ(subjectInfoVOList);
    }








    private  Boolean insertLeaderInfoToGroup(String username,int i){
        QueryWrapper<SelectSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_id",username);
        SelectSubject subject = selectSubjectService.getOne(queryWrapper);
        String subjectId = subject.getSubjectId();
        String courseClassId = subject.getCourseClassId();
        boolean isSave = setGroupLeader(subjectId,courseClassId,username,i);
        return isSave;

    }
    private boolean setGroupLeader(String subjectId,String courseClassId,String username,int i){
        QueryWrapper<SubjectGroup> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("course_class_id",courseClassId);
        queryWrapper.eq("subject_id",subjectId);
        SubjectGroup subjectGroup = subjectGroupService.getOne(queryWrapper);
        if(i ==1){
            subjectGroup.setGroupLeader(username);
        }else{
            subjectGroup.setGroupLeader("");
        }
        boolean b = subjectGroupService.updateById(subjectGroup);
        System.out.println(b);
        return b;

    }



}
